package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    @Override
    public List<Menu> getMenus(String username) {
        List<Menu> allMenu = getAllMenus();
        List<Menu> userMenus = menuDao.findMenuByUsername(username);
        Iterator<Menu> l1iter = allMenu.iterator();
        while (l1iter.hasNext()) {
            Menu l1Menu = l1iter.next();
            if (null != l1Menu.getChildren() && l1Menu.getChildren().size() > 0) {
                Iterator<Menu> l2Iter = l1Menu.getChildren().iterator();
                while (l2Iter.hasNext()) {
                    Menu l2Menu = l2Iter.next();
                    boolean flag = false;
                    for (Menu userMenu : userMenus) {
                        if (userMenu.getId().equals(l2Menu.getId())) {
                            flag = true;
                        }
                    }
                    if (!flag) {
                        l2Iter.remove();
                    }
                }
            }
            if (l1Menu.getChildren().size() == 0) {
                l1iter.remove();
            }
        }
        return allMenu;
    }

    private List<Menu> getAllMenus() {
        List<Menu> all = menuDao.findAll();
        Map<Integer, Menu> relationMap = new HashMap<>();
        for (Menu menu : all) {
            relationMap.put(menu.getId(), menu);
        }
        Menu root = new Menu();
        root.setChildren(new ArrayList<Menu>());
        relationMap.put(0, root);
        for (Menu menu : all) {
            if (null == menu.getParentMenuId()) {
                root.getChildren().add(menu);
                continue;
            }
            Menu parent = relationMap.get(menu.getParentMenuId());
            if (null != parent) {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<Menu>());
                }
                parent.getChildren().add(menu);
            }
        }
        return root.getChildren();
    }
}
